/*
 * @Description: 当好设置面板
 * @Author: Rfan
 * @Date: 2022-02-10 09:30:53
 * @LastEditTime: 2022-09-08 14:30:17
 */

import { FC, useEffect, useState } from 'react';
import { Alert, Button, Checkbox, Form, Input, Select, Space } from 'antd';
import classNames from 'classnames/bind';
import { fetchMetadata } from '@/api/metadata';
import { selectItemByKey } from '@/utils/list';
import { isNullObj } from '@/utils';
import { useArchivalCodeContext } from '../contexts/ArchivalCodeContext';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import styles from '../styles/archiveCodePane.module.scss';

const cx = classNames.bind(styles);
const { Option } = Select;

export type ArchiveCodePaneProps = {
  title?: string;
  data?: any;
};

const ArchiveCodePane: FC<ArchiveCodePaneProps> = (props) => {
  const { selectFond, selectAT, initRule, addArcnoRule, editArcnoRule } = useArchivalCodeContext();
  const [form] = Form.useForm();
  const [fieldList, setFieldList] = useState([]);
  const [saveFlag, setSaveFlag] = useState<boolean>(false);
  const [expId, setExpId] = useState('');
  const [expName, setExpName] = useState('');
  const [expDesc, setExpDesc] = useState('');
  const [fullRule, setFullRule] = useState('');

  useEffect(() => {
    // 切换档案类型后重置表单
    clearRules();
    setSaveFlag(false);
    if (JSON.stringify(selectAT) !== '{}') {
      // 切换档案类型后请求该档案类型的元数据列表
      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_ALL,
        coordinate: {
          atType: selectAT.atType,
          atCode: selectAT.atCode,
          level: selectAT.atLevel
        }
      };
      fetchMetadata(fieldQuery).then((res) => {
        setFieldList(res.data);
      });
    }
  }, [selectAT, selectFond]);

  /**
   * @description: 请求到规则后重置表单
   */
  useEffect(() => {
    clearRules();
    console.log('initRuleChange', initRule, expDesc);
    if (JSON.stringify(initRule) !== '{}') {
      setStrsSplit(initRule.ruleExpressIds, initRule.ruleExpressUse, initRule.ruleExpressShow);
      // 解决新增、编辑后规则表达式字段重复的问题，强制重写表单字段
      // 原因：useState异步更新，form赋值时 expDesc 不是最新状态
      form.setFieldsValue({ condition: initRule.ruleExpressShow });
      setFullRule(initRule.ruleExpressShow);
    }
  }, [initRule]);

  /**
   * @description: 请求到规则后重置表单
   */
  useEffect(() => {
    if (JSON.stringify(selectAT) !== '{}') {
      setSaveFlag(!(expName === initRule?.ruleExpressUse));
    }
  }, [expName]);

  const setStrsSplit = (id: string, name: string, desc: string, field?: string) => {
    setExpId((state) => state + id);
    setExpName((state) => state + name);
    setExpDesc((state) => state + desc);
    form.setFieldsValue({ condition: expDesc + desc });
    setFullRule(expDesc + desc);
    field && form.setFieldsValue({ [field]: '' });
  };

  /**
   * @description: 通用增加字符串方法
   * @param {string} value 更新的值
   * @param {string} field 更新之后需要清空的表单
   */
  const setStrs = (value: string, field?: string) => {
    if (value) {
      setStrsSplit(value, value, value, field);
    }
  };

  /**
   * @description: 拼接字符
   */
  const joinConstStr = () => {
    const constStr = form.getFieldValue('constStr');
    setStrs(constStr, 'constStr');
  };

  /**
   * @description: 拼接连接符
   */
  const joinMarkStr = () => {
    const condMark = form.getFieldValue('condMark');
    setStrs(condMark, 'condMark');
  };

  /**
   * @description: 拼接字段
   */
  const joinFieldStr = () => {
    const id = form.getFieldValue('condField');
    if (id) {
      const condField: any = selectItemByKey(parseInt(id, 10), fieldList);
      setStrsSplit(
        `[${condField.id}]`,
        `[${condField.field_name}]`,
        `[${condField.field_desc}]`,
        'condField'
      );
    }
  };

  /**
   * @description: 清空规则方法
   */
  const clearRules = () => {
    setExpId('');
    setExpName('');
    setExpDesc('');
    form.setFieldsValue({ condition: '' });
  };

  const saveRules = () => {
    const query: any = {
      ruleExpressIds: expId,
      ruleExpressShow: expDesc,
      ruleExpressUse: expName
    };
    if (!isNullObj(initRule) && initRule.id) {
      query.id = initRule.id;
      editArcnoRule(query).then(() => {
        setSaveFlag(false);
      });
    } else {
      addArcnoRule(query).then(() => {
        setSaveFlag(false);
      });
    }
  };

  return (
    <div className={cx('archive-code-pane')}>
      <div className={cx('tips')}>
        <Alert
          description={
            <span>
              档号是<strong>必要的著录信息</strong>
              ，档号的构成需要参照档案标准来确定，一般是由档案的几个字段组合而成；通常如果按案卷管理的档案，只需要指定案卷的档号，案卷内文件的档号默认处理为案卷档号+卷内序号。
            </span>
          }
          type="info"
          showIcon
          closable
        />
      </div>
      <div className={cx('container')}>
        <div className={cx('archive-code-header')}>
          <div className={cx('title')}>档号-表达式设置</div>
          <div className={cx('operate')}>
            <Space>
              <Button disabled>使用模板</Button>
              <Button disabled>保存为模板</Button>
              <Button disabled={!saveFlag} onClick={saveRules}>
                保存
              </Button>
            </Space>
          </div>
        </div>
        <Form labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} preserve={false} form={form}>
          <Form.Item label="使用对象">{selectAT.atName}</Form.Item>
          <Form.Item
            label="规则表达式"
            extra="输入字符串、连接符或选择字符，分别点击拼接，可生成档案规则的表达式"
            required
          >
            <Space>
              <Form.Item name="condition" noStyle rules={[{ required: true, message: '' }]}>
                <Input title={fullRule} disabled />
              </Form.Item>
              <Button type="primary" onClick={clearRules}>
                清空规则
              </Button>
            </Space>
          </Form.Item>
          <Form.Item label="输入字符串" extra="字符串是档号规则中固定不变的部分">
            <Space>
              <Form.Item name="constStr" noStyle>
                <Input />
              </Form.Item>
              <Button type="primary" onClick={joinConstStr}>
                点击拼接
              </Button>
            </Space>
          </Form.Item>
          <Form.Item label="输入连接符" extra='链接符是档号的分隔符，如"+"、"-"等等'>
            <Space>
              <Form.Item name="condMark" noStyle>
                <Input />
              </Form.Item>
              <Button type="primary" onClick={joinMarkStr}>
                点击拼接
              </Button>
            </Space>
          </Form.Item>
          <Form.Item label="选择字段">
            <Space>
              <Form.Item name="condField" noStyle>
                <Select style={{ width: 120 }}>
                  {fieldList.map((field) => (
                    <Option key={field.id} label={field.id}>
                      {field.field_desc}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Button type="primary" onClick={joinFieldStr}>
                点击拼接
              </Button>
            </Space>
          </Form.Item>
          <Form.Item label="是否重复">
            <div>档案在整编库中不做沿革的重复检查，归档库则每次修改都会检查</div>
            <Form.Item name="fondName" noStyle>
              <div>
                用于整编库 <Checkbox>档号不允许重复</Checkbox>
              </div>
            </Form.Item>
            <Form.Item name="fondName1" noStyle>
              <div>
                用于归档库 <Checkbox>档号不允许重复</Checkbox>
              </div>
            </Form.Item>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default ArchiveCodePane;
